﻿using HandyControl.Controls;
using HandyControl.Themes;
using HandyControl.Tools;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Random
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : HandyControl.Controls.Window
    {
        private int go1ClickCount = 0;
        private int go2ClickCount = 0;

        AppSprite sprite;

        private bool CanSwitchTabs = true;

        private DispatcherTimer timer1 = new DispatcherTimer();
        private DispatcherTimer timer2 = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();
            sprite = new AppSprite();
        }

        private void InitRandom()
        {
            if (maxnump.Value - minnump.Value + 1 >= 10)
            {
                int removeAt;
                List<int> ints = Enumerable.Range((int)minnump.Value, (int)(maxnump.Value - minnump.Value + 1)).ToList();
                System.Random rd = new System.Random();
                for (int i = 1; i <= 10; i++)
                {
                    removeAt = rd.Next(0, ints.Count);
                    var textBox = (TextBlock)FindName("T" + i);
                    textBox.Text = Convert.ToString(ints[removeAt]);
                    ints.RemoveAt(removeAt);
                    Thread.Sleep(10);
                }
            }
            else
            {
                System.Random rd = new System.Random();
                //T1.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T2.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T3.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T4.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T5.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T6.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T7.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T8.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T9.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                //T10.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                for (int i = 1; i <= 10; i++)
                {
                    var textBox = (TextBlock)FindName("T" + i);
                    textBox.Text = Convert.ToString(rd.Next((int)minnump.Value, (int)maxnump.Value + 1));
                    //Thread.Sleep(10);
                }
            }
        }
        private void StartSlowingDownTimer(DispatcherTimer timer, Action onTimerStopped)
        {
            int interval = (int)Math.Round(timer.Interval.TotalMilliseconds, MidpointRounding.AwayFromZero);
            timer.Tick += (s, args) =>
            {
                if (interval < 750) // 确保间隔不会小于50毫秒
                {
                    interval = (int)Math.Min(int.MaxValue, interval * 1.5); // 增加计时器间隔，实现减速效果
                    timer.Interval = TimeSpan.FromMilliseconds(interval);
                }
                else
                {
                    timer.Stop();
                    timer = new DispatcherTimer();
                    onTimerStopped?.Invoke(); // 执行计时器停止后的操作
                }
            };
            timer.Start();
        }
        private void Go1_Click(object sender, RoutedEventArgs e)
        {
            if (fastmode.IsChecked == true ? true : false)
            {
                g1();
            }
            else
            {
                timer1.Interval = TimeSpan.FromMilliseconds(70);
                go1ClickCount++;
                if (go1ClickCount == 1)
                {
                    timer1 = new DispatcherTimer();
                    timer1.Interval = TimeSpan.FromMilliseconds(70);
                    // 设置计时器，开始循环生成随机数
                    timer1.Tick += (s, args) => g1();
                    timer1.Start();
                    Go1.Content = "停止！";
                    fastmode.IsEnabled = false;
                    CanSwitchTabs = false;
                }
                else
                {
                    timer1.Tick -= (s, args) => g1();
                    // 第二次点击，开始减速直到停止
                    StartSlowingDownTimer(timer1, () =>
                    {
                        Go1.IsEnabled = true;
                    });
                    go1ClickCount = 0; // 重置点击计数
                    Go1.Content = "开始！";
                    fastmode.IsEnabled = true;
                    CanSwitchTabs = true;
                    Go1.IsEnabled = false;
                }
            }
        }
        void g1()
        {
            System.Random rd = new System.Random();
            end1.Content = Convert.ToString(rd.Next((int)minnum.Value, ((int)maxnum.Value) + 1));
        }

        void g2()
        {
            System.Random rd = new System.Random();
            int 行num;
            int 列num;
            if (行.IsChecked == true && 列.IsChecked == true)
            {
                行num = rd.Next(1, Convert.ToInt32(行数.Value) + 1);
                列num = rd.Next(1, Convert.ToInt32(列数.Value) + 1);
                end2.Content = Convert.ToString(列num) + "列" + Convert.ToString(行num) + "行";
            }
            else
            {
                if (行.IsChecked == true && 列.IsChecked == false)
                {
                    行num = rd.Next(1, Convert.ToInt32(行数.Value) + 1);
                    end2.Content = Convert.ToString(行num) + "行";
                }
                else
                {
                    if (行.IsChecked == false && 列.IsChecked == true)
                    {
                        列num = rd.Next(1, Convert.ToInt32(列数.Value) + 1);
                        end2.Content = Convert.ToString(列num) + "列";
                    }
                }
            }
        }
        private void Go2_Click(object sender, EventArgs e)
        {
            if (fastmode.IsChecked == true ? true : false)
            {
                g2();
            }
            else
            {
                timer2.Interval = TimeSpan.FromMilliseconds(70);
                go2ClickCount++;
                if (go2ClickCount == 1)
                {
                    timer2 = new DispatcherTimer();
                    timer2.Interval = TimeSpan.FromMilliseconds(70);
                    // 设置计时器，开始循环生成随机数
                    timer2.Tick += (s, args) => g2();
                    timer2.Start();
                    Go2.Content = "停止！";
                    fastmode.IsEnabled = false;
                    CanSwitchTabs = false;
                }
                else
                {
                    go2ClickCount = 0; // 重置点击计数
                    Go2.Content = "开始！";
                    fastmode.IsEnabled = true;
                    CanSwitchTabs = true;
                    Go2.IsEnabled = false;
                    // 第二次点击，开始减速直到停止
                    StartSlowingDownTimer(timer2, () =>
                    {
                        Go2.IsEnabled = true;
                    });
                }
            }
        }

        private void main_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SaveSettings();
        }

        private void main_Loaded(object sender, RoutedEventArgs e)
        {
            LoadSettings();
            InitRandom();
        }

        private void LoadSettings()
        {
            minnum.Value = Properties.Settings.Default.MinNum;
            maxnum.Value = Properties.Settings.Default.MaxNum;

            行数.Value = Properties.Settings.Default.RowCount;
            列数.Value = Properties.Settings.Default.ColumnCount;

            nightmod.IsChecked = Properties.Settings.Default.NightMode;

            minnump.Value = Properties.Settings.Default.MinNumP;
            maxnump.Value = Properties.Settings.Default.MaxNumP;

            行.IsChecked = Properties.Settings.Default.RowCheck;
            列.IsChecked = Properties.Settings.Default.ColumnCheck;
            IsTop.IsChecked = Properties.Settings.Default.Top;
            IsGo2.IsChecked = Properties.Settings.Default.IsSpriteGo2Mod;
            GlobalVariables.spriteIsGo2 = IsGo2.IsChecked == true;
            syschange.IsChecked = Properties.Settings.Default.SysChangeColor;
            if (syschange.IsChecked == true)
            {
                autocolor();
            }
            fastmode.IsChecked = Properties.Settings.Default.FastMode;
            if (fastmode.IsChecked == true)
            {
                Go1.Content = "挑选！";
                Go2.Content = "抽取！";
            }
            else
            {
                Go1.Content = "开始！";
                Go2.Content = "开始！";
            }
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.MinNum = minnum.Value;
            Properties.Settings.Default.MaxNum = maxnum.Value;
            Properties.Settings.Default.RowCount = 行数.Value;
            Properties.Settings.Default.ColumnCount = 列数.Value;
            Properties.Settings.Default.RowCheck = 行.IsChecked == true;
            Properties.Settings.Default.ColumnCheck = 列.IsChecked == true;
            Properties.Settings.Default.FastMode = fastmode.IsChecked == true;
            Properties.Settings.Default.NightMode = nightmod.IsChecked == true;
            Properties.Settings.Default.MinNumP = minnump.Value;
            Properties.Settings.Default.MaxNumP = maxnump.Value;
            Properties.Settings.Default.SysChangeColor = syschange.IsChecked == true;
            Properties.Settings.Default.Top = IsTop.IsChecked == true;
            Properties.Settings.Default.IsSpriteGo2Mod = IsGo2.IsChecked == true;

            Properties.Settings.Default.Save();
        }

        private void nightmod_Checked(object sender, RoutedEventArgs e)
        {
            if (syschange.IsChecked == false)
            {
                ThemeManager.Current.ApplicationTheme = ApplicationTheme.Dark;
            }
            else
            {
                if (!(IsNightMod() == true))
                {
                    syschange.IsChecked = false;
                    ThemeManager.Current.ApplicationTheme = ApplicationTheme.Dark;
                }
            }
        }

        private void nightmod_Unchecked(object sender, RoutedEventArgs e)
        {
            if (syschange.IsChecked == false)
            {
                ThemeManager.Current.ApplicationTheme = ApplicationTheme.Light;
            }
            else
            {
                if (!(IsNightMod() == false))
                {
                    syschange.IsChecked = false;
                    ThemeManager.Current.ApplicationTheme = ApplicationTheme.Light;
                }
            }
        }

        private void fastmode_Checked(object sender, RoutedEventArgs e)
        {
            if (fastmode.IsChecked == true ? true : false)
            {
                Go1.Content = "挑选！";
                Go2.Content = "抽取！";
            }
            else
            {
                Go1.Content = "开始！";
                Go2.Content = "开始！";
            }
        }

        private void GroupBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TB1.IsChecked = true;
            TB2.IsChecked = true;
            TB3.IsChecked = true;
            TB4.IsChecked = true;
            TB5.IsChecked = true;
            TB6.IsChecked = true;
            TB7.IsChecked = true;
            TB8.IsChecked = true;
            TB9.IsChecked = true;
            TB10.IsChecked = true;
            InitRandom();
        }

        private void opensprite_Click(object sender, RoutedEventArgs e)
        {
            Sprite.Show(sprite);
            GlobalVariables.isSpriteOpen = true;
            reloadminmax();
            reloadhanglie();
        }

        private void syschange_Checked(object sender, RoutedEventArgs e)
        {
            autocolor();
        }
        private void autocolor()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize");
            if (key != null)
            {
                int theme = (int)key.GetValue("AppsUseLightTheme", -1);//0暗1亮
                ThemeManager.Current.ApplicationTheme = theme == 0 ? ApplicationTheme.Dark : ApplicationTheme.Light;
                nightmod.IsChecked = theme == 0;
                key.Close();
            }
        }
        private bool? IsNightMod()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize");
            if (key != null)
            {
                int theme = (int)key.GetValue("AppsUseLightTheme", -1);//0暗1亮
                key.Close();
                return theme == 0;
            }
            else
            {
                return null;
            }
        }

        private void minnum_ValueChanged(object sender, HandyControl.Data.FunctionEventArgs<double> e)
        {
            reloadminmax();
        }

        private void maxnum_ValueChanged(object sender, HandyControl.Data.FunctionEventArgs<double> e)
        {
            reloadminmax();
        }
        private void reloadminmax()
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.min = (int)minnum.Value;
                sprite.max = (int)maxnum.Value;
            }
        }

        private void reloadhanglie()
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.hang = (int)行数.Value;
                sprite.lie = (int)列数.Value;
            }
        }

        private void IsGo2_Checked(object sender, RoutedEventArgs e)
        {
            GlobalVariables.spriteIsGo2 = true;
        }

        private void IsGo2_Unchecked(object sender, RoutedEventArgs e)
        {
            GlobalVariables.spriteIsGo2 = false;
        }

        private void 行数_ValueChanged(object sender, HandyControl.Data.FunctionEventArgs<double> e)
        {
            reloadhanglie();
        }

        private void 列数_ValueChanged(object sender, HandyControl.Data.FunctionEventArgs<double> e)
        {
            reloadhanglie();
        }

        private void 列_Checked(object sender, RoutedEventArgs e)
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.islie = true;
            }
        }

        private void 列_Unchecked(object sender, RoutedEventArgs e)
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.islie = false;
            }
        }

        private void 行_Checked(object sender, RoutedEventArgs e)
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.ishang = true;
            }
        }

        private void 行_Unchecked(object sender, RoutedEventArgs e)
        {
            if (GlobalVariables.isSpriteOpen)
            {
                sprite.ishang = false;
            }
        }
        private void website_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.windflag.xyz/");
        }
    }
}
